package com.zch.rpc.core.net.jetty2;


import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;

import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Auther: zch
 * @Date: 2018/12/28 13:50
 * @Description:
 */
public class JettyServer implements com.zch.rpc.core.net.abstracts.Server {
    private Logger logger= LoggerFactory.getLogger(JettyServer.class);
    private int port;

    public JettyServer(int port) {
        this.port = port;
    }

    private Thread thread;

    public void start()  {

        thread = new Thread(new Runnable() {

            @Override
            public void run() {

                // The Server
                org.eclipse.jetty.server.Server server= new org.eclipse.jetty.server.Server(new QueuedThreadPool());	// default maxThreads 200, minThreads 8
                // HTTP connector
                ServerConnector connector = new ServerConnector(server);

                connector.setPort(port);
                server.setConnectors(new Connector[]{connector});

                // Set a handler
                HandlerCollection handlerc =new HandlerCollection();
                handlerc.setHandlers(new Handler[]{new JettyServerHandler()});
                server.setHandler(handlerc);

                try {
                    server.start();

                   // logger.info(">>>>>>>>>>> rpc remoting server start success, nettype = {}, port = {}", JettyServer.class.getName(), xxlRpcProviderFactory.getPort());

                    server.join();
                } catch (Exception e) {
                    if (e instanceof InterruptedException) {
                        logger.info(">>>>>>>>>>> rpc remoting server stop.");
                    } else {
                        logger.error(">>>>>>>>>>> rpc remoting server error.", e);
                    }
                } finally {
                    if (server!=null && server.isRunning()) {
                        try {
                            server.stop();
                            server.destroy();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
            }
        });
        thread.setDaemon(true);	// daemon, service jvm, user thread leave >>> daemon leave >>> jvm leave
        thread.start();
    }


    /*public void stop() throws Exception {

        // destroy server thread
        if (thread!=null && thread.isAlive()) {
            thread.interrupt();
        }

        // on stop
        onStoped();
        logger.info(">>>>>>>>>>> rpc remoting server destroy success.");
    }*/
}
